<?php
/**
 * Date: 2017/11/10
 * Time: 10:08
 * Author: zeronlee
 */

namespace App\Http\Controllers\Backend;


use App\Http\Controllers\Controller;
use App\Models\Access\User\User;
use App\Models\Ogz;
use App\Models\App;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Http\Controllers\Traits\Base;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Traits\Users;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Cache;

class QyappController extends Controller
{
    use Base,Users;
    /**
     * 首页
     */
    public function index (){
        //机构列表
        $fields = ['o.id','o.name','o.pid'];
        $ogzs = $this->getOgzs($fields,[0=>['o.deleted_at','==','NULL']]);
        $pageNum = 10;
        //联系人列表
        $users = $this->getUsers();

        return view('backend.qyapp.appindex')->with('users',\GuzzleHttp\json_encode($users))
            ->with('ogzs',\GuzzleHttp\json_encode($ogzs))
            ->with('pageNum',$pageNum);
    }
    /**
     * 添加页面
     */
    public function addPage (){
        //机构列表
        $fields = ['o.id','o.name','o.pid'];
        $ogzs = $this->getOgzs($fields,[0=>['o.deleted_at','==','NULL']]);
        //联系人列表
        $users = $this->getUsers();
        $pageData = ['ogzs' => $ogzs,'users' => $users,'type'=>App::$type,'is_foreign' => App::$is_foreign,'ogzsJson' =>json_encode($ogzs)];

        return view('backend.qyapp.addpage',$pageData);
    }
    /**
     * 编辑页面
     */
    public function editPage (Request $request){
        //机构列表
        $fields = ['o.id','o.name','o.pid'];
        $ogzs = $this->getOgzs($fields,[0=>['o.deleted_at','==','NULL']]);
        //联系人列表
        $users = $this->getUsers();
        $item = App::find($request->id);

        $pageData = ['ogzs' => $ogzs,'users' => $users,'type'=>App::$type,'is_foreign' => App::$is_foreign,'ogzsJson' =>json_encode($ogzs),'row'=>$item];
        return view('backend.qyapp.editpage',$pageData);
    }
    /**
     * 内容页
     */
    public function search (Request $request){
        $param = $request->input();

        //列表
        $fields = ['a.id','a.name','a.description','a.sort','a.ogz_id','u.id as user_id','u.name as user_name','o.name as ogz_name','a.deleted_at','a.user_id as many_user'];
        //多条件搜索
        $search = $param['search'];
        //默认值
        $search['value'] = empty($search['value']) ? '1&' : $search['value'];
        //搜索值按页面搜索框从左到右
        $filter = explode('&',$search['value']);
        //搜索
        $where = [];
        //搜索禁用标识
        $searchDisabled = false;
        //迭代条件
        if ($filter[0]==1){

            $where[0] = ['a.deleted_at','==','NULL'];
        }
        if ($filter[0]==2){
            $searchDisabled = true;
            $where[0] = ['a.deleted_at','!=','NULL'];
        }
        if (isset($filter[1]) && $filter[1]){
            $where[1] = [['a.name','like','%'.$filter[1].'%'],['a.description','like','%'.$filter[1].'%']];
        }
        //全局条件
        $where[2] = ['a.id',access()->hasApps($searchDisabled)];
        //记录数
        $count = App::getList($fields,$where,true);

        $apps = App::getList($fields,$where,false,[$param['start'],$param['length']]);
        foreach ($apps as $app){

            $app->user_name = $this->getUserName($app->many_user);
        }
        Cache::put('searchAppWhere',$where,10);
        $data = array('draw'=>intval($param['draw']),'recordsTotal'=>$count,'recordsFiltered'=>$count,'data'=>$apps);

        return response()->json($data);
    }
    /**
     * 数据验证
     */
    public function validateForm ($request,$type='add') {

        $this->validate($request, [
            'ogz_id' => 'required|integer|min:1',
            'name' => ['required',Rule::unique('app')->ignore($request->id)],
            'description' => 'required',
            'user_id' => 'required|array'
        ], [
            'ogz_id.required' => '请选择父机构',
            'ogz_id.integer' => '请选择父机构',
            'ogz_id.min' => '请选择父机构',
            'name.required' => '请填写名称',
            'name.unique' => '该名称已存在',
            'description.required' => '请填写描述',
            'user_id.required' => '请选择联系人'
        ]);
    }

    /**
     * 全局数据验证
     */
    public function scopeValid ($data,$handleName='addOrUpdate'){
        $res = ['code'=>0];
        //user_id
        $links = $this->userLinks();
        //需要启用权限
        $links['apps'] = access()->hasApps(true);
        if ($handleName == 'del') {
            //app_id
            if (!in_array($data['id'],$links['apps'])){
                $res['code'] = 403;
                $res['msg'] = '没有权限操作该应用';
            }
        }else{
            //ogz_id
            if (!in_array($data['ogz_id'],$links['ogzs']['child'])){
                $res['code'] = 403;
                $res['msg'] = '没有权限选择该机构';
            }
            //user_id
            $users = $this->getUsers();
            $hasUser = 0;
            foreach ($data['user_id'] as $item){

                foreach ($users as $user){
                    if ($user->id == $item){
                        $hasUser++;
                    }
                }
            }
            if ($hasUser != count($data['user_id'])){
                $res['code'] = 403;
                $res['msg'] = '没有权限选择该用户';
            }
        }
        return $res;
    }
    /**
     * 添加机构
     */
    public function add (Request $request){
        $res['code'] = 0;
        $this->validateForm($request);
        $valider = $this->scopeValid($request->input(),'add');
        if ($valider['code']!==0){
            $res['code'] = $valider['code'];
            $res['msg']  = $valider['msg'];
        }else{
            $data = $request->input();
            //如何自定义错误json返回
            $data['sort'] = 0;
            unset($data['id']);
            $data['user_id'] = implode(',',$data['user_id']);
            if (!App::insertRow($data)){
                $res['code'] = 500;
                $res['msg'] = '添加失败';
            }
        }
        if ($res['code']>0)
            return redirect('admin/qyappaddpage')->withErrors($res['msg'])->withInput();
        return redirect('/admin/qyappIndex');
    }
    /**
     * 修改机构
     */
    public function update (Request $request){
        $res['code'] = 0;
        $this->validateForm($request,'update');
        $param = $request->input();
        $valider = $this->scopeValid($request->input(),'update');
        if ($valider['code']!==0){
            $res['code'] = $valider['code'];
            $res['msg']  = $valider['msg'];
        }else{
            $param['updated_at'] = Carbon::now();
            $param['user_id'] = implode(',',$param['user_id']);
            $app = new App();
            if(!$app->updateRow(array('id',$param['id']),$param)){
                $res['code'] = 500;
                $res['msg']  = '编辑失败';
            }
        }
        if ($res['code']>0)
            return redirect('admin/qyappaddpage')->withErrors($res['msg'])->withInput();
        return redirect('/admin/qyappIndex');
    }
    /**
     * 删除机构
     */
    public function delete (Request $request){
        $app = new App();

        $data['code'] = 0;
        $valider = $this->scopeValid($request->input(),'del');
        if ($valider['code']!==0){
            $data['code'] = $valider['code'];
            $data['msg']  = $valider['msg'];
        }else{
            try{
                $app->deleteRow($request);

            }catch (\Exception $e){
                $data['code'] = 403;//非法操作

                $data['msg'] = $e->getMessage();

            }
        }
        return response()->json($data);
    }
    /**
     * 激活
     */
    public function active (Request $request){
        $data['code'] = 0;
        //软删除
        $valider = $this->scopeValid($request->input(),'del');
        if ($valider['code']!==0){
            $data['code'] = $valider['code'];
            $data['msg']  = $valider['msg'];
        }else{
            $app = new App();
            if (!$app->activeRow($request)){
                $data['code'] = 500;
                $data['msg'] = '服务器忙';
            }
        }
        return response()->json($data);
    }
    /**
     * 导出
     */
    public function export(){
        $excelTitle = '机构与应用联系人';
        $excelData = [];
        //机构和应用都需要导出
        //每个联系人一行
        $where = Cache::get('searchAppWhere');
        $sel = ['id','name','user_id','uet','type','is_foreign','etv','address','ops','msv','lvv','ut'];
        if ($where[0][1] == '!=') {

            $excelData = $this->onlyTrash();
            $extData = App::select($sel)->onlyTrashed()->get();
        } else {
            $excelData = $this->noTrash();
            $extData = App::select($sel)->get();
        }
        //转换成一维
        $exportData = [];
        foreach ($excelData as $_data){
            foreach ($_data as $its){

                $exportData[] = $its;
            }
        }
        foreach ($extData as $exts => $ext){
            $ext->typeStr = intval($ext->type)>0 ? App::$type[$ext->type] : '';
            $ext->is_foreignStr = intval($ext->is_foreign) ? App::$is_foreign[$ext->is_foreign] : '';
            $ext->userStr = User::getNameString(explode(',',$ext->user_id));
            $ext->addressArr = strpos($ext->address,"\r\n") ? explode("\r\n",$ext->address) : ['',''];
            $ext->opsArr = strpos($ext->ops,"\r\n") ? explode("\r\n",$ext->ops) : ['',''];
            $ext->msvArr = strpos($ext->msv,"\r\n") ? explode("\r\n",$ext->msv) : ['',''];
            $ext->lvvArr = strpos($ext->lvv,"\r\n") ? explode("\r\n",$ext->lvv) : ['',''];
            $ext->utArr  = strpos($ext->ut,"\r\n")  ? explode("\r\n",$ext->ut)  : ['',''];
        }
        Excel::create($excelTitle, function ($excel)use($exportData,$extData) {

            $excel->sheet('应用联系人', function ($sheet)use($exportData,$extData) {

                $sheet->loadView('excel.appexport',array('data' => $exportData));

            });
            $excel->sheet('应用补充信息', function ($sheet)use($exportData,$extData) {

                $sheet->loadView('excel.appext',array('data' => $extData));

            });
        })->export('xls');
    }
    /**
     * 导出禁用数据
     */
    private function onlyTrash (){
        $excelData = [];
        $trashed = Ogz::onlyTrashed()->whereIn('id',access()->hasOgzs(true))->get();
        foreach ($trashed as $item) {

            $parents = array_reverse(Ogz::getParent($item->pid,true));
            $deepArr = [];
            foreach ($parents as $p){
                $deepArr[] = Ogz::where(['id'=>$p])->withTrashed()->first();
            }
            $excelData[] = $this->exportData($item,$deepArr);

        }
        $trashedApp = App::onlyTrashed()->whereIn('id',access()->hasApps(true))->get();
        foreach ($trashedApp as $app) {

            $parentsOgz = array_reverse(Ogz::getParent($app->ogz_id,true));
            $deepArr = [];
            foreach ($parentsOgz as $p1){
                $deepArr[] = Ogz::where(['id'=>$p1])->withTrashed()->first();
            }
            $excelData[] = $this->exportData($app,$deepArr,true);

        }
        return $excelData;
    }
    /**
     * 导出正常状态数据
     */
    private function noTrash (){
        $excelData = [];
        $group = Ogz::getCollectWithSel(['id','name','user_id'],['pid'=>0]);

        foreach ($group as $k => $item){

            $excelData[] = $this->exportData($item);

            //app info
            $appObj = App::getCollectWithSel(['id','name','user_id'],['ogz_id'=>$item->id]);
            foreach ($appObj as $app){

                $excelData[] = $this->exportData($app,[$item],true);
            }
            //板块
            $subtemp = Ogz::getCollectWithSel(['id','name','user_id'],['pid'=>$item->id]);
            foreach ($subtemp as $v1) {
                $excelData[] = $this->exportData($v1);

                //app info
                $appObj1 = App::getCollectWithSel(['id','name','user_id'],['ogz_id'=>$v1->id]);
                foreach ($appObj1 as $app1){

                    $excelData[] = $this->exportData($app1,[$v1],true);
                }
                //公司
                $company = Ogz::getCollectWithSel(['id','name','user_id'],['pid'=>$v1->id]);
                foreach ($company as $v2) {
                    $excelData[] = $this->exportData($v2,[$v1]);
                    //app info
                    $appObj2 = App::getCollectWithSel(['id','name','user_id'],['ogz_id'=>$v2->id]);
                    foreach ($appObj2 as $app2){

                        $excelData[] = $this->exportData($app2,[$v1,$v2],true);
                    }
                    //子公司
                    $subcompany = Ogz::getCollectWithSel(['id','name','user_id'],['pid'=>$v2->id]);
                    foreach ($subcompany as $v3) {
                        $excelData[] = $this->exportData($v3,[$v1,$v2]);
                        $appObj3 = App::getCollectWithSel(['id','name','user_id'],['ogz_id'=>$v3->id]);
                        foreach ($appObj3 as $app3){

                            $excelData[] = $this->exportData($app3,[$v1,$v2,$v3],true);
                        }
                    }
                }
            }
        }
        return $excelData;
    }
    /**
     * 导出联系人数据结构
     */
    private function exportData ($item,$deepArr =[],$isApp=false){
        $ret = [];
        if ($item) {
            if ($deepArr) {
                //parent
                foreach ($deepArr as $k => $value) {

                    $elm[$k] = $value->name;

                }
                //'-'补齐
                if ($isApp) {
                    $count = 3;
                    $elm[3] = $item->name;
                }else {
                    //self
                    $elm[++$k] = $item->name;
                    $count = 4;
                }
                for ($i = ++$k; $i < $count; $i++) {
                    $elm[$i] = '-';
                }

            }else {

                $elm = [$item->name, '-', '-', '-'];
            }
            if (trim($item->user_id)) {

                $users = explode(',', $item->user_id);
                //一个用户一行
                $tempUser = [];
                foreach ($users as $user) {
                    //string of name email phone
                    $userObj = User::select(['name', 'email', 'phone'])->where('id', $user)->first();
                    if(!empty($userObj)){

                        $tempUser[] =$userObj->name . '（' . decrypt_func($userObj->email, $userObj->name) . '、' . decrypt_func($userObj->phone, $userObj->name) . '）';

                    }
                }
                foreach ($tempUser as $us){
                    $elmTemp = $elm;
                    array_push($elmTemp,$us);

                    ksort($elmTemp);
                    $ret[] = $elmTemp;
                }

            }else {
                array_push($elm, '-');
                ksort($elm);
                $ret[] = $elm;
            }
        }

        return $ret;
    }
}